!
!  munimatch    finding of cross identification between two lists
!
!  Copyright © 2010 F.Hroch (hroch@physics.muni.cz)
!
!  This file is part of Munipack.
!
!  Munipack is free software: you can redistribute it and/or modify
!  it under the terms of the GNU General Public License as published by
!  the Free Software Foundation, either version 3 of the License, or
!  (at your option) any later version.
!  
!  Munipack is distributed in the hope that it will be useful,
!  but WITHOUT ANY WARRANTY; without even the implied warranty of
!  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
!  GNU General Public License for more details.
!  
!  You should have received a copy of the GNU General Public License
!  along with Munipack.  If not, see <http://www.gnu.org/licenses/>.


program munimatch

  use input
  use matchsolve

  implicit none

  integer :: ninput = 100
  integer :: nmatch = 7
  real :: uradius = 0.01
  real, dimension(:),allocatable :: x1,y1,x2,y2
  integer, dimension(:), allocatable :: id1,id2
  integer :: i,n
  character(len=32768) :: record,line,key,value
  real :: s0

  allocate(x1(ninput),y1(ninput),x2(ninput),y2(ninput))

  n = 0
  do
     read(*,'(a)',iostat=i,end=20) record
     if( i /= 0 ) stop 'Failed to read of a current input record.'

!     write(*,*) trim(record)

     call input_rcomment(record,line)

     select case(input_classify(line))
        
     case(input_key)

        call input_keys(line,key,value)
        
        if( key == 'Input stars' )then
           read(value,*) ninput
           deallocate(x1,y1,x2,y2)
           allocate(x1(ninput),y1(ninput),x2(ninput),y2(ninput))
        end if

        if( key == 'Match sequence' )then
           read(value,*) nmatch
        end if

        if( key == 'Uncertainty radius' )then
           read(value,*) uradius           
        end if

     case (input_data)

        n = n + 1
!        write(*,*) n,trim(line)
        if( n > ninput ) goto 20
        read(line,*) x1(n),y1(n),x2(n),y2(n)
        
     end select

  end do

20 continue
!20 n = n - 1

  call solvepar(nmatch,uradius)

!  allocate(id(n))
  call solve(x1(1:n),y1(1:n),x2(1:n),y2(1:n),id1,id2,s0)

!  do i = 1, n
!     write(*,*) x1(i),y1(i),x2(i),y2(i)
!  end do

  do i = 1, size(id1)
     write(*,*) id1(i), id2(i)
  end do
  write(*,*) s0

  deallocate(x1,y1,x2,y2)
  deallocate(id1,id2)

end program munimatch

